package org.eclipse.jdt.internal.ui.callhierarchy;

import org.eclipse.core.runtime.NullProgressMonitor;

import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;


/**
 * lombok重构
 * .
 * @author hehuang 20180222
 *
 */
public class LombokRefactor {

	/**
	 * 按照结构进行重构,需要重构的部分包括import和字段
	 * .
	 * @param compilationUnit
	 */
	public void refactor(ICompilationUnit compilationUnit) throws JavaModelException {
		
		// 处理import
		IImportDeclaration[] importDeclarations = compilationUnit.getImports();
		if (importDeclarations != null
				&& importDeclarations.length > 0) {
			for (IImportDeclaration importDeclaration
					: importDeclarations) {
				refactor(importDeclaration);
			}
		}
		
		// 处理字段
		IType[] types = compilationUnit.getAllTypes();
		if (types != null
				&& types.length > 0) {
			for (IType type 
					: types) {
				refactor(type);
			}
		}
		
	}
	
	public void refactor(IImportDeclaration importDeclaration) throws JavaModelException {
		if ("lombok.Getter".equals(
				importDeclaration.getElementName())
				|| "lombok.Setter".equals(
						importDeclaration.getElementName())) {
			importDeclaration.delete(true, new NullProgressMonitor());
		}
	}
	
	public void refactor(IType type) throws JavaModelException {
		IField[] fields = type.getFields();
		
		if (fields != null
				&& fields.length > 0) {
			for (IField field
					: fields) {
				refactor(field);
			}
		}
	}
	
	public void refactor(IField field) throws JavaModelException {
		FieldLombokRefactorBuilder fieldRefactorBuilder = FieldLombokRefactorBuilder.getInstance();
		
		if (fieldRefactorBuilder != null) {
			FieldLombokRefactor refactor = fieldRefactorBuilder.buildFieldRefactor(field);
			
			if (refactor != null) {
				refactor.refactor(field);
			}
		}
	}
}
